﻿using Business;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MvcAppWeb.Controllers
{
    public class PurchaseSumController : Controller
    {
        //
        // GET: /PurchaseSum/

        public ActionResult PurchaseInOutSum()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                VenderUser model = (VenderUser)Session["UserInfo"];
                return View(model);
            }
        }

        /// <summary>
        /// 查询
        /// </summary> 
        public JsonResult Query(string OrderNoOrGoodsCode, DateTime CheckTimeS, DateTime CheckTimeE)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            VenderUser model = (VenderUser)Session["UserInfo"];
            string where = "";//and rt.venderid=" + model.VENDERID;

            //管理员测试数据放开
            if (model.USERCODE != "system")
            {
                where += " and vd.venderid=" + model.VENDERID;
            }
            if (!string.IsNullOrEmpty(OrderNoOrGoodsCode))
            {
                where += " and PurInOut.sheetid='" + OrderNoOrGoodsCode + "'";
            }
            if (CheckTimeS != null)
            {
                where += " and PurInOut.CheckDate>= to_date('" + CheckTimeS + "','yyyy-mm-dd hh24:mi:ss')";
            }
            if (CheckTimeE != null)
            {
                where += " and PurInOut.CheckDate<= to_date('" + CheckTimeE + "','yyyy-mm-dd hh24:mi:ss')";
            }
            where += " order by PurInOut.CheckDate DESC";
            Dictionary<string, decimal> dicTotalField = new Dictionary<string, decimal>();
            dicTotalField.Add("*", 0);
            dicTotalField.Add("TOTALQTY", 0);
            dicTotalField.Add("TOTALCOSTVALUE", 0);
            dicTotalField.Add("TOTALCOSTTAXVALUE", 0);
            BPurchaseInOutSum ogc = new BPurchaseInOutSum();
            List<PurchaseInOutSumInfo> result = ogc.GetPurchaseSumList2(page, rows, ref dicTotalField, where);

            PurchaseInOutSumInfo PursumItem = new PurchaseInOutSumInfo(); 
            PursumItem.TotalQty = result.Sum(x => x.TotalQty);
            PursumItem.TotalCostValue = result.Sum(x => x.TotalCostValue);
            PursumItem.TotalCostTaxValue = result.Sum(x => x.TotalCostTaxValue); 
            PursumItem.SheetID = "当前页总合计：";
            result.Add(PursumItem);
            PurchaseInOutSumInfo PursumItem2 = new PurchaseInOutSumInfo();
            PursumItem2.TotalQty = dicTotalField["TOTALQTY"];
            PursumItem2.TotalCostValue = dicTotalField["TOTALCOSTVALUE"];
            PursumItem2.TotalCostTaxValue = dicTotalField["TOTALCOSTTAXVALUE"]; 
            PursumItem2.SheetID = "所有页总合计：";
            result.Add(PursumItem2);
            total = Convert.ToInt32(dicTotalField["*"]);
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);

            
            
        }


        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpPost]
        public FileResult ExportExcel(int page, int rows)//导出execl
        {
            //int page = int.Parse(Request["page"].ToString());
            //int rows = int.Parse(Request["rows"].ToString());
            int total = 0;

            string OrderNoOrGoodsCode = Request["txtOrdSubjectCode"]; 
            DateTime CheckTimeS = Convert.ToDateTime(Request["CheckTimeS"]);
            DateTime CheckTimeE = Convert.ToDateTime(Request["CheckTimeE"]);
            VenderUser model = (VenderUser)Session["UserInfo"];

            string where = "";//and  rt.venderid=" + model.VENDERID;
            //管理员测试数据放开
            if (model.USERCODE != "system")
            {
                where += " and vd.venderid=" + model.VENDERID;
            }
            if (!string.IsNullOrEmpty(OrderNoOrGoodsCode))
            {
                where += " and PurInOut.sheetid='" + OrderNoOrGoodsCode + "'";
            } 
            if (CheckTimeS != null)
            {
                where += " and PurInOut.CheckDate>= to_date('" + CheckTimeS + "','yyyy-mm-dd hh24:mi:ss')";
            }
            if (CheckTimeE != null)
            {
                where += " and PurInOut.CheckDate<= to_date('" + CheckTimeE + "','yyyy-mm-dd hh24:mi:ss')";
            }
            where += " order by PurInOut.CheckDate DESC";
            BPurchaseInOutSum ogc = new BPurchaseInOutSum();
            List<PurchaseInOutSumInfo> list = ogc.GetPurchaseSumList(page, rows, out total, where);
             
            var sbHtml = new StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "采购进/退单号", "单据类型", "结算方式", "总数量", "总金额", "总税额","下单时间", "订单状态", "供应商" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count(); i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].SheetID); 
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].OrderType);
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].PayTypeName);
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].TotalQty);
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].TotalCostValue);
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].TotalCostTaxValue); 
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].CheckDate);
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", FormatFlag(list[i].Flag)); 
                sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", list[i].VenderName); 
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", "fileContents.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
        }

        private string FormatFlag(int flag)
        {
            string str = string.Empty;
            if (flag == 20)
            {
                str = "待处理";
            }
            if (flag == 40)
            {
                str = "在执行";
            }
            if (flag == 100)
            {
                str = "完结";
            }
            if (flag == 90)
            {
                str = "已审核";
            }
            return str;
        }

    }
}
